package org.jet.emall.reptile.downloader;

import com.github.pagehelper.PageHelper;
import org.jet.emall.mapper.TbProdSkuImageMapper;
import org.jet.emall.mapper.TbProdSkuMapper;
import org.jet.emall.mapper.TbProdSpuImageMapper;
import org.jet.emall.mapper.TbProdSpuMapper;
import org.jet.emall.po.*;
import org.jet.emall.reptile.pojo.ImageModel;
import org.jet.emall.reptile.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class ImageDownloaderImpl implements ImageDownloader {

    @Autowired
    private TbProdSkuImageMapper prodSkuImageMapper;

    @Autowired
    private TbProdSpuImageMapper prodSpuImageMapper;

    @Autowired
    private TbProdSkuMapper prodSkuMapper;

    @Autowired
    private TbProdSpuMapper prodSpuMapper;

    ExecutorService threadPool = Executors.newFixedThreadPool(20);

    @Value("${fetcher.jd.imagesDir}")
    private String imagesDir;

    private long count = 0;



    synchronized private long addCount(){
        count++;
        return count;
    }

    @Override
    public void download() {
        //downloadSpuImages();
        downloadSkuImages();
        while (true){
            try {
                Thread.sleep(30000);
                System.out.println("主线程["+Thread.currentThread().getId()+"]正在等待中....count=["+count+"].....................................");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }



    private void downloadSpuImages(){
        File file = new File(imagesDir);
        if (!file.exists()) {
            file.mkdir();
        }
        int pageSize = 50;
        System.out.println("开始SPU下载图片");
        long totals = prodSpuMapper.countByExample(null);
        for (int pageNum = 1; ; pageNum++) {
            if((pageNum-1)*pageSize > totals ) {
                break;
            }
            final int num = pageNum;
            threadPool.execute(() -> {
                PageHelper.startPage(num, pageSize);

                List<TbProdSpu> tbProdSpus = prodSpuMapper.selectByExample(null);
                TbProdSpuImageExample ex = new TbProdSpuImageExample();
                for (TbProdSpu tbProdSpu : tbProdSpus) {
                    ex.clear();
                    ex.createCriteria().andSpuIdEqualTo(tbProdSpu.getId());
                    List<TbProdSpuImage> tbProdSpuImages = prodSpuImageMapper.selectByExample(ex);
                    for (TbProdSpuImage tbProdSpuImage : tbProdSpuImages) {
                        try {
                            saveFile(imagesDir,tbProdSpuImage.getImage());

                        } catch (IOException e) {
                            e.printStackTrace();
                            continue;
                        }

                    }
                }
            });
        }
    }


    private void downloadSkuImages(){
        File file = new File(imagesDir);
        if (!file.exists()) {
            file.mkdir();
        }
        int pageSize = 100;
        System.out.println("开始下载图片");
        long totals = prodSkuMapper.countByExample(null);
        for (int pageNum = 1; ; pageNum++) {
            if((pageNum-1)*pageSize > totals ) {
                break;
            }
            int num = pageNum;
            threadPool.execute(() -> {
                PageHelper.startPage(num, pageSize);
                List<TbProdSku> tbProdSkus = prodSkuMapper.selectByExample(null);
                TbProdSkuImageExample ex = new TbProdSkuImageExample();
                for (TbProdSku tbProdSku : tbProdSkus) {
                    ex.clear();
                    ex.createCriteria().andSkuIdEqualTo(tbProdSku.getId())
                            .andLargeImageIsNotNull();
                    List<TbProdSkuImage> tbProdSkuImages = prodSkuImageMapper.selectByExample(ex);
                    //System.out.println("images="+tbProdSkuImages);

                    String flag = ".com/";
                    TbProdSkuImageExample ex2 = new TbProdSkuImageExample();

                    Couple couple = getCoupleFrom(tbProdSkuImages.get(0).getImage(),
                            tbProdSkuImages.get(0).getLargeImage());
                    ex2.clear();
                    ex2.createCriteria().andSkuIdEqualTo(tbProdSku.getId());
                    List<TbProdSkuImage> prodSkuImageList = prodSkuImageMapper.selectByExample(ex2);
                    for (TbProdSkuImage tbProdSkuImage : prodSkuImageList) {
                        if(tbProdSkuImage.getLargeImage()==null) {
                            //tbProdSkuImage.setLargeImage(tbProdSkuImage.getImage().replace(couple.s1, couple.s2));
                            int end = tbProdSkuImage.getImage().indexOf(flag);
                            String s1 = tbProdSkuImage.getImage().substring(0,end);
                            String s2 = tbProdSkuImage.getImage().substring(end).replaceFirst(couple.s1,couple.s2);
                            tbProdSkuImage.setLargeImage(s1+s2);
                            prodSkuImageMapper.updateByPrimaryKey(tbProdSkuImage);
                        }

                        //System.out.println("skuImage="+tbProdSkuImage);
//                            try {
//                                saveFile(imagesDir,tbProdSkuImage.getImage());
//                                saveFile(imagesDir,tbProdSkuImage.getLargeImage());
//                            } catch (IOException e) {
//                                e.printStackTrace();
//                                continue;
//                            }
                    }
                }
            });

        }


    }

    class Couple {
        String s1;
        String s2;
    }

    private Couple getCoupleFrom(String str1, String str2) {
        Couple couple = new Couple();
        couple.s1 = getSubString(str1, str2);
        couple.s2 = getSubString(str2, str1);
        return couple;
    }

    private String getSubString(String str1, String str2) {
        int begin = 0;
        for (int i = 0; i < str1.length(); i++) {
            if (str1.charAt(i) != str2.charAt(i)) {
                begin = i;
                break;
            }
        }

        int end = 0;
        for (int j = str1.length() - 1, k = str2.length() - 1; j >= 0 && k >= 0; j--, k--) {
            if (str1.charAt(j) != str2.charAt(k)) {
                end = j;
                break;
            }
        }

        return str1.substring(begin, end + 1);
    }

    private boolean isFileExist(String imagesDir,String url){
        String flag = ".com/";
        String filePath = imagesDir + "/"+ url.substring(url.indexOf(flag) + flag.length());
        File file = new File(filePath);
        return file.exists();
    }


    private void saveFile(String imagesDir, String url) throws IOException {
        if(isFileExist(imagesDir,url)){
            System.out.println("文件已存在............");
            return;
        }

        ImageModel imageModel = HttpClientUtils.doDownloadImage(url);
        String filePath = imagesDir + "/" + imageModel.getFileName();
        String dir = filePath.substring(0, filePath.lastIndexOf("/"));
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File file = new File(filePath);
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
        outputStream.write(imageModel.getData());
        outputStream.flush();
        System.out.println("线程["+Thread.currentThread().getId()+"]保存第["+addCount()+"]张图片,imagePath="+filePath);

    }

}
